package com.microservice.common.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 图形验证码工具类
 */
public class CaptchaUtil {
    
    // 验证码字符集（排除容易混淆的字符如0,O,1,l等）
    private static final String CAPTCHA_CHARS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    
    // 验证码长度
    private static final int CAPTCHA_LENGTH = 4;
    
    // 图片宽度
    private static final int WIDTH = 120;
    
    // 图片高度
    private static final int HEIGHT = 40;
    
    // 干扰线数量
    private static final int LINE_COUNT = 5;
    
    private static final Random random = new Random();
    
    /**
     * 生成验证码文本
     * 
     * @return 验证码字符串
     */
    public static String generateCaptchaText() {
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < CAPTCHA_LENGTH; i++) {
            captcha.append(CAPTCHA_CHARS.charAt(random.nextInt(CAPTCHA_CHARS.length())));
        }
        return captcha.toString();
    }
    
    /**
     * 生成验证码图片
     * 
     * @param captchaText 验证码文本
     * @return 图片字节数组
     */
    public static byte[] generateCaptchaImage(String captchaText) throws IOException {
        // 创建图片缓冲区
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        
        // 设置抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
        // 填充背景色（渐变色）
        GradientPaint gp = new GradientPaint(0, 0, new Color(240, 240, 240), 
                                              WIDTH, HEIGHT, new Color(255, 255, 255));
        g.setPaint(gp);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        // 绘制边框
        g.setColor(new Color(200, 200, 200));
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
        
        // 绘制干扰线
        for (int i = 0; i < LINE_COUNT; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g.setColor(getRandomColor(180, 220));
            g.drawLine(x1, y1, x2, y2);
        }
        
        // 绘制验证码字符
        int charWidth = WIDTH / CAPTCHA_LENGTH;
        for (int i = 0; i < captchaText.length(); i++) {
            // 随机字体
            String[] fonts = {"Arial", "Verdana", "Tahoma", "Georgia"};
            Font font = new Font(fonts[random.nextInt(fonts.length)], 
                               Font.BOLD, 24 + random.nextInt(4));
            g.setFont(font);
            
            // 随机颜色
            g.setColor(getRandomColor(20, 130));
            
            // 随机旋转角度
            double theta = (random.nextInt(30) - 15) * Math.PI / 180;
            
            char c = captchaText.charAt(i);
            int x = i * charWidth + charWidth / 4 + random.nextInt(5);
            int y = HEIGHT / 2 + random.nextInt(10);
            
            // 应用旋转
            g.rotate(theta, x, y);
            g.drawString(String.valueOf(c), x, y);
            g.rotate(-theta, x, y);
        }
        
        // 绘制干扰点
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            g.setColor(getRandomColor(150, 200));
            g.fillRect(x, y, 2, 2);
        }
        
        g.dispose();
        
        // 将图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }
    
    /**
     * 获取随机颜色
     * 
     * @param min 最小RGB值
     * @param max 最大RGB值
     * @return 随机颜色
     */
    private static Color getRandomColor(int min, int max) {
        if (min > 255) min = 255;
        if (max > 255) max = 255;
        
        int r = min + random.nextInt(max - min);
        int g = min + random.nextInt(max - min);
        int b = min + random.nextInt(max - min);
        
        return new Color(r, g, b);
    }
}
